package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"users/model"
	"users/pkg"

	"users/usersrpc/internal/svc"
	"users/usersrpc/usersrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserAuthLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserAuthLogic {
	return &UserAuthLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserAuthLogic) UserAuth(in *usersrpc.UserAuthRequest) (*usersrpc.UserAuthResponse, error) {
	// todo: add your logic here and delete this line
	var user model.User
	Data, err := user.FindAurh(in.UserId)
	if err != nil {
		return nil, err
	}
	if Data.ID == 0 {
		return nil, fmt.Errorf("用户不存在")
	}
	if Data.IdCard != "" {
		return nil, fmt.Errorf("用户已经实名认证")
	}
	err = pkg.UserAuth(in.IdCard, in.RealName)
	if err != nil {
		return nil, err
	}
	users := &model.User{
		Model:    gorm.Model{ID: uint(in.UserId)},
		IdCard:   in.IdCard,
		RealName: in.RealName,
	}
	err = users.UpDataUser()
	if err != nil {
		return nil, fmt.Errorf("实名认证失败")
	}
	return &usersrpc.UserAuthResponse{
		UserId: int64(users.ID),
	}, nil
}
